<?php

declare(strict_types=1);

namespace App\Command\Admin;

use App\Constants\Rbac\AdminCode;
use App\Service\Admin\AdminService;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;

#[Command]
class AdminCommand extends HyperfCommand
{

    protected ?string $signature = 'admin:util {method}';

//    public function __construct(protected ContainerInterface $container)
//    {
//        parent::__construct('admin:util {method}');
//    }
//
//    public function configure()
//    {
//        parent::configure();
//        $this->setDescription('Hyperf Demo Command');
//    }

    public function handle()
    {
        $method = $this->input->getArgument('method');
        if (method_exists($this, $method)){
            $this->{$method}();
        }else{
            $this->output->warning('method '. $method.' not exists');
        }
    }

    protected function create()
    {
        $account = $this->askMust('登录账号');
        $secret = $this->askMust('登录密码');
        $nickname = $this->askMust('昵称');
        $isRoot = $this->confirm('是否超级管理员',true);
        if (!$isRoot){
            $roleIds = $this->askMust('role_ids,英文逗号隔开');
            $roleIds = explode(',', $roleIds);
        }else{
            $roleIds = [];
        }
        $isRoot = $isRoot ? AdminCode::IS_ROOT : AdminCode::IS_NORMAL;
        [$r, $msg] = \Hyperf\Support\make(AdminService::class)->addAdmin([
            'account' => $account,
            'login_pwd' => $secret,
            'nickname' => $nickname,
            'is_root' => $isRoot,
            'role_ids' => $roleIds,
        ]);
        if ($r){
            $this->info($msg);
        }else{
            $this->warn($msg);
        }
    }

    protected function askMust($msg)
    {
        $res = $this->ask($msg);
        if (empty($res)){
            $this->askMust($msg);
        }
        return $res;
    }

}
